package com.itzg.vboxfarm.service;

import java.util.LinkedHashMap;
import java.util.Map;

import org.springframework.stereotype.Service;
import org.virtualbox_4_1.IVirtualBox;
import org.virtualbox_4_1.VBoxException;
import org.virtualbox_4_1.VirtualBoxManager;

import com.itzg.vboxfarm.domain.HostMachine;

@Service
public class VirtualBoxManagerService {

	private Map<IVirtualBox, VirtualBoxManager> managersForVboxes = 
			new LinkedHashMap<IVirtualBox, VirtualBoxManager>();

	public IVirtualBox createConnection(HostMachine hostMachine) throws VBoxException {
		VirtualBoxManager vboxManager = VirtualBoxManager.createInstance(null);
		vboxManager.connect("http://" + hostMachine.getHostname() + ":"
				+ hostMachine.getWsPort(), hostMachine.getWsUsername(),
				hostMachine.getWsPassword());

		IVirtualBox vBox = vboxManager.getVBox();
		managersForVboxes.put(vBox, vboxManager);
		return vBox;
	}
	
	public void releaseConnection(IVirtualBox vbox) {
		VirtualBoxManager manager = managersForVboxes.remove(vbox);
		vbox.releaseRemote();
		manager.disconnect();
	}
}
